<!--  核销申请-->
<template>
  <a-card :bordered='false'>
    <!-- 查询区域 -->
    <search ref='search' :config='searchConfig' @search='search' @getHeight='getHeight' />

    <!-- table区域-begin -->
    <div class='page_table'>
      <vxe-grid
        ref='xGrid'
        v-bind='vexConfig'
        :align='left'
        :border='true'
        :checkbox-config='checkboxConfig'
        :columns='columns'
        :data='dataSource'
        :height='pageHeight-seachHeight-94'
        :loading='loading'
        :resizable='true'
        :showOverflow='true'
        :toolbar-config='tableToolbar'
        size='mini'
        @checkbox-change='selectChangeEvent'
        @checkbox-all='selectChangeEvent'
      >
        <template #toolbar_buttons>
          <!-- 操作按钮区域 -->
          <div class='table-operator'>
            <a-button v-has="'feeApply:close'" type='primary' @click='handleClose'>核销关闭</a-button>
            <a-button v-has="'feeApply:passs'" type='primary' @click='handleRedeal'>审批通过</a-button>
            <a-button v-has="'feeApply:special'" :disabled='selectedRowKeys.length !== 1' type='primary'
                      @click='handleAddStore'>
              核销特批
            </a-button>
            <a-button v-has="'feeApply:getOut'" type='primary' @click="downExportXls('tpmAudit_service')">导出
            </a-button>
          </div>
        </template>
        <template #actName='{ row,rowIndex }'>
          <a @click='handleEdit(row,"detail")'>{{ row.actName }}</a>
        </template>
        <template #action='{ row:record }' >
          <span v-if='record.bpmStatus === 1 || record.bpmStatus === 4'>
            <a @click='handleEdit(record)'>编辑</a>
          <a-divider type='vertical' />
          <a-dropdown>
            <a class='ant-dropdown-link'>
              更多
              <a-icon type='down' />
            </a>
            <a-menu slot='overlay'>
              <a-menu-item>
                <a @click='addToStop(record,"checks")'>提交审批</a>
              </a-menu-item>
            </a-menu>
          </a-dropdown>
          </span>
        </template>

        <template #pager>
          <vxe-pager
            :currentPage.sync='ipagination.current'
            :layouts="['Total', 'PrevJump', 'PrevPage', 'Number', 'NextPage', 'NextJump','Sizes', 'FullJump']"
            :page-size.sync='ipagination.pageSize'
            :pageSizes='ipagination.pageSizeOptions'
            :total='ipagination.total'
            @page-change='handlePageChange'>
          </vxe-pager>
        </template>
      </vxe-grid>
    </div>
    <!-- table区域-end -->

    <feeApplyModal ref='modalForm' @ok='modalFormOk'></feeApplyModal>
    <form-add-edit ref='popupForm' @ok='modelFormOkss'></form-add-edit>
  </a-card>
</template>

<script>
import { PageListMixin } from '@/mixins/PageListMixin'
import { getAction, postAction } from '@api/manage'
import feeApplyModal from '@/views/tmr/payCenter/modules/feeApplyModal'
import HpayselectCom from '@/components/cn-components/HpayselectCom'
import formAddEdit from '@comp/view/base-crud/form/FormAddEdit'


export default {
  name: 'activityApplication',
  mixins: [PageListMixin],
  components: {
    feeApplyModal,
    HpayselectCom,
    formAddEdit
  },
  data() {
    return {
      permflag: 'audit_impl',
      loading: false,
      description: '核销申请页面',
      searchConfig: [
        {
          // label:'订单编号',
          type: 'input',
          name: 'actCode',
          placeholder: '活动编码'
        }, {
          // label:'业务员',
          type: 'input',
          name: 'actName',
          placeholder: '活动名称'
        },
        {
          // label:'订单编号',
          type: 'input',
          name: 'auditCode',
          placeholder: '核销申请编码'
        },
        {
          // label:'订单状态',
          type: 'j-select',
          name: 'bpmStatus',
          dictCode: 'tpm_bpm_status',
          placeholder: '审批状态'
        }, {
          // label:'售达方编码',
          type: 'date-range',
          name: 'kunnr',
          range: ['auditStartDate', 'auditEndDate'],// 后台接受字段
          placeholder: ['开始时间', '结束时间']
        }, {
          type: 'tree-select',
          placeholder: '申请人组织',
          dataType: 'org',
          name: 'actOrgCode'  // 后台接受字段
        }, {
          // label:'出库时间',
          type: 'input',
          name: 'auditApplyUser',
          placeholder: '申请人姓名'
        }
      ],
      // 表头
      columns: [
        { type: 'checkbox', width: 50, fixed: null ,field: 'a',},
        {
          title: '流程编号',
          minWidth: 80,
          field: 'processKey'
        },
        {
          title: '活动名称',
          minWidth: 80,
          field: 'actName',
          slots: { default: 'actName' },
        },
        {
          title: '核销申请编码',
          minWidth: 120,
          field: 'auditCode'
        },
        {
          title: '活动编码',
          minWidth: 80,
          field: 'actCode'
        },
        {
          title: '核销申请时间',
          minWidth: 120,
          field: 'auditApplyTime'
        },
        {
          title: '流程提交时间',
          minWidth: 120,
          field: 'bpmSubmitTime'
        },
        {
          title: '核销申请人',
          minWidth: 100,
          field: 'auditApplyUser'
        },
        {
          title: '申请人所在组织',
          minWidth: 140,
          field: 'actOrgName'
        },
        {
          title: '关闭原因',
          minWidth: 80,
          field: 'closingInstructions'
        },
        {
          title: '备注',
          minWidth: 80,
          field: 'remarks'
        },
        {
          title: '审批状态',
          fixed: 'right',
          minWidth: 120,
          field: 'bpmStatusStr'
        },
        {
          title: '操作',
          field: 'action',
          fixed: 'right',
          minWidth: 120,
          slots: { default: 'action' },
        }
      ],
      url: {
        list: window._CONFIG['domianTpmURL'] + '/tpmAudit/findPageList',
        detail: window._CONFIG['domianTpmURL'] + '/tpmAudit/getAuditDetail',
        closeOne: window._CONFIG['domianTpmURL'] + '/tpmAudit/closeAudit',
        stopOne: window._CONFIG['domianTpmURL'] + '/tpmAudit/takeBackAudit',
        checks: window._CONFIG['domianTpmURL'] + '/tpmAudit/commitAudit',
        deals: window._CONFIG['domianTpmURL'] + '/tpmAudit/approvedToAccount',


        exportXlsUrl: window._CONFIG['domianTpmURL'] + 'budget/tpmBudgetFee/exportXls',
        deleteBatch: window._CONFIG['domianTpmURL'] + '/activity/delete'
      },
      closeReason: ''
    }
  },
  methods: {
    modelFormOkss(val) {
      let record = val
      val.id = this.selectedRowKeys[0]
      let url = window._CONFIG['domianTpmURL'] + '/tpmAudit/commitAuditExamined'
      getAction(url, { ...val }).then(res => {
        if (res.success) {
          this.$message.info(res.message)
        } else {
          this.$message.error(res.message)
        }
      }).finally(() => {
        this.$refs.popupForm.confirmLoading = false
        this.$refs.popupForm.close()
        this.loadData()
      })
    },
    handleAddStore() {
      if (this.selectionRows[0].bpmStatus == 2 || this.selectionRows[0].bpmStatus == 3) {
        this.$message.info('请确认活动状态')
        return
      }
      let config = {
        title: '新增特批理由',
        width: 500,
        list: [
          {
            label: '特批理由',
            type: 'textarea',
            placeholder: '请输入特批理由',
            name: 'remarks',  // 后台接受字段
            check: { rules: [{ required: true, message: '请输入特批理由' }] }
          }
        ]
      }
      this.$refs.popupForm.edit({}, config)
      this.$refs.popupForm.disableSubmit = false
    },
    handleSpecial() {
      let url = window._CONFIG['domianTpmURL'] + '/tpmAudit/commitAuditExamined'
      getAction(url, { id: this.selectedRowKeys[0] }).then(res => {
        res.success ? this.$message.info(res.message) : this.$message.error(res.message)
      })
    },
    handleRedeal() {
      if (this.selectedRowKeys.length < 1) {
        this.$message.info('请至少选择一项')
        return
      }
      let ids = ' '
      let that = this
      ids = this.selectedRowKeys.join(',').toString()
      getAction(that.url.deals, { ids: ids }).then(res => {
        if (res.success) {
          that.$message.success(res.message)
          that.loadData()
        } else {
          that.$message.warning(res.message)
        }
      })
    },
    addToStop(record, status) {
      let url = ''
      if (status == 'stopOne') {
        url = this.url.stopOne
      } else if (status == 'checks') {
        url = this.url.checks
      }
      let that = this
      getAction(url, { id: record.id }).then((res) => {
        if (res.success) {
          that.$message.success(res.message)
          that.loadData()
        } else {
          that.$message.warning(res.message)
        }
      })
    },
    // customRowFn(record) {
    //   return {
    //     on: {
    //       click: () => {
    //         this.selectedRowKeys = [record.id]
    //         this.selectionRows = [record]
    //       }
    //     }
    //   }
    // },
    onSelectChange2(selectedRowKeys, selectionRows) {
      this.selectedRowKeys2 = selectedRowKeys
      this.selectionRows2 = selectionRows
    },
    handleClose: function() {
      if (this.selectedRowKeys.length <= 0) {
        this.$message.warning('请选择一条记录！')

      } else {
        let rows = this.selectionRows
        let ids = this.selectionRows[this.selectedRowKeys.length - 1].id
        var that = this
        this.$confirm({
          title: `是否关闭 [ ${this.selectionRows[this.selectedRowKeys.length - 1].actName} ] ?`,
          content: this.$createElement('a-input', {
            attrs: {
              placeholder: '请输入关闭原因'
            },
            domProps: {
              value: that.closeReason || '',
              type: 'text'
            },
            on: {
              input: function(e) {
                that.closeReason = e.target.value
              }
            }
          }),
          onOk: function() {
            if (that.closeReason == '') {
              that.$message.info('请输入关闭原因')
              return Promise.reject()
            } else {
              that.loading = true
              getAction(that.url.closeOne, { id: ids, closingInstructions: that.closeReason }).then((res) => {
                if (res.success) {
                  that.$message.success(res.message)
                  that.loadData()
                } else {
                  that.$message.warning(res.message)
                }
              }).finally(() => {
                that.loading = false
                that.closeReason == ''
              })
            }

          }
        })
      }
    },
    handleEdit: async function(record, status) {
      if (this.url.detail) {
        const res = await getAction(this.url.detail, { id: record.id })
        if (res.success) {
          record = res.result
        } else {
          this.$message.error(res.message)
        }
      }
      if (status == 'detail') {
        this.$refs.modalForm.edit(record)
        this.$refs.modalForm.title = '详情'
        this.$refs.modalForm.disableSubmit = true
        this.$refs.modalForm.unOrDown = false
        this.$refs.modalForm.unDownUrl = false
        this.$refs.modalForm.unOrDowntitle = '点击下载'
      } else {
        this.$refs.modalForm.edit(record)
        this.$refs.modalForm.title = '编辑'
        this.$refs.modalForm.disableSubmit = false
        this.$refs.modalForm.unOrDown = true
        this.$refs.modalForm.unDownUrl = true
        this.$refs.modalForm.unOrDowntitle = '点击上传'
      }
    }

  },
  created() {
    this.queryParam.doc = '订货单'

  },


  // beforeMount() {
  //   const draggingMap = {};
  //   this.columns.forEach((col) => {
  //     draggingMap[col.field] = col.width;
  //   });
  //   const draggingState = Vue.observable(draggingMap);
  //   const resizeableTitle = (h, props, children) => {
  //     let thDom = null;
  //     const { key, ...restProps } = props;
  //     console.log(props)
  //     let col;
  //     // 复选框筛选处理
  //     if (key === 'selection-column') {
  //       col = {};
  //     } else {
  //       col = this.columns.find((item) => {
  //         const k = item.field || item.key;
  //         return k === key;
  //       });
  //     }
  //     // 未设置宽度或者设置不可伸缩时不做伸缩处理
  //     if (!col.width || col.noStretch) {
  //       return <th {...restProps}>{children}</th>;
  //     }
  //     const onDrag = (x) => {
  //       draggingState[key] = 0;
  //       // 设置一个伸缩的最小宽度，防止页面错乱
  //       col.width = Math.max(x, col.minWidth || 30);
  //     };
  //     const onDragstop = () => {
  //       draggingState[key] = thDom.getBoundingClientRect().width;
  //     };
  //     return (
  //       <th
  //         {...restProps}
  //         v-ant-ref={(r) => (thDom = r)}
  //         width={col.width}
  //         class="resize-table-th"
  //       >
  //         {children}
  //         <vue-draggable-resizable
  //           key={col.key}
  //           class="table-draggable-handle"
  //           w={10}
  //           x={col.width||draggingState[key]}
  //           z={1}
  //           axis="x"
  //           draggable={true}
  //           resizable={false}
  //           onDragging={onDrag}
  //           onDragstop={onDragstop}
  //         />
  //       </th>
  //     );
  //   };
  //   this.components = {
  //     header: {
  //       cell: resizeableTitle,
  //     },
  //   };
  // },


  watch: {
    // pageHeight(val){
    //   // 为了避免频繁触发resize函数导致页面卡顿，使用定时器
    //   if(!this.timer){
    //     // 一旦监听到的screenWidth值改变，就将其重新赋给data里的screenWidth
    //     this.pageHeight = val
    //     this.timer = true
    //     let that = this
    //     setTimeout(function(){
    //       // 打印screenWidth变化的值
    //       console.log(that.pageHeight)
    //       that.timer = false
    //     },100)
    //   }
    // }
  },
  computed: {
    importExcelUrl: function() {
      return `${window._CONFIG['domianURL']}/${this.url.importExcelUrl}`
    }
  }
}
</script>

<style lang='less' scoped>
@import '~@assets/less/common.less';

/deep/ .ant-pagination {
  float: right;
}

///deep/ .resize-table-th {
//  position: relative;
//}
///deep/ .table-draggable-handle {
//  height: 100% !important;
//  bottom: 0;
//  left: auto !important;
//  right: -5px;
//  cursor: col-resize;
//  touch-action: none;
//}

</style>